﻿using System;
using System.Linq;
using Fee.Orders.DesignWorkflow;

namespace Fee.Orders
{
    /// <summary>
    ///     预委托单得批量号
    /// </summary>
    public class DelegateOrderBatchGenerator
    {
        private int? _number;


        protected int GetLastWorkflowInstance(FeeDbContext entry)
        {
            lock (this)
            {
                var now = DateTime.Today.AddDays(1);
                var last = entry.Set<BudgetOrder>().OrderByDescending(f => f.CreateTime)
                    .FirstOrDefault(f => f.BatchNo != null && f.CreateTime < now);
                if (last != null)
                    if (!string.IsNullOrEmpty(last.Number))
                        return ToIndex(last.Number, entry);

                return 0;
            }
        }

        protected virtual int ToIndex(string number, FeeDbContext entry)
        {
            return Convert.ToInt32(number.Substring(10).TrimStart('0'));
        }

        protected virtual string GeneratorNumber(int index, FeeDbContext entry)
        {
            return "WB" + DateTime.Today.ToString("yyyyMMdd") + (++_number).ToString().PadLeft(5, '0');
        }

        public string Next(FeeDbContext entry)
        {
            lock (this)
            {
                //F 20190101 index(5)
                if (_number == null) _number = GetLastWorkflowInstance(entry);

                _number++;
                return GeneratorNumber(_number.Value, entry);
            }
        }
    }
}